/* Copyright Andy Mitchell 2007. No warranties */

function ContactsUI(gtdinboxPage){
	this._gtdinboxPage = gtdinboxPage;
	this._doc = gtdinboxPage.doc;
	this._labels = gtdinboxPage._labels;
	this._eventObservers = new EventObservers(this);
	this._selected = [];	// [[name,email,elInput]]
	this._showHiders = [];
};

ContactsUI.prototype.viewChange = function(){
	// Called when switch to contacts view
	// See if installed into environment,
	// If not, add listeners for check boxes and tabs
	//	And add a pane for viewing
try{
	if( this._elPaneContent ){	// Already loaded; ensure still in view
		var el = this._elPaneContent;
		var foundBody = false;
		while( el.parentNode ){
			el = el.parentNode;
			if( el.nodeName=="BODY" ){
				foundBody = true;
				break;
			}
		}
		if( foundBody ){
			this.refreshPane();
			return;
		}
	}
	
	// Extract the body
	var w = this._gtdinboxPage.window.frames[1];
	for( var i = 0; i < w.frames.length; i++ ){
		if( w.frames[i].location.href=="about:blank" ){
			var onLoad = GIPROTOTYPE.bind(this, function(){
				if( this._elContactsBody ) return;
				this._elContactsBody = this._gtdinboxPage.gmailDOM.element("contacts-frame-body");
				this._contactsDoc = this._elContactsBody.ownerDocument;
				this._gtdinboxPage.addCSS(this._contactsDoc);
				setTimeout( GIPROTOTYPE.bind(this, this._parseEnvironment), 2000 );
			});
			this._eventObservers.observe( w.frames[i], "load", onLoad, false);
		}
	}
	
	
}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI viewChage\n" + e.toString());
}
};
ContactsUI.prototype._parseEnvironment = function(inCallback){
	// Extract elements from the contacts box
	
try{
	this._elManagerTabs = this._gtdinboxPage.gmailDOM.element("contacts-manager-tabs", null, this._contactsDoc, this._elContactsBody);
	this._elManagerList = this._gtdinboxPage.gmailDOM.element("contacts-manager-list", null, this._contactsDoc, this._elContactsBody);
	this._elPane = this._gtdinboxPage.gmailDOM.element("contacts-pane", null, this._contactsDoc, this._elContactsBody);
	
	// Safety check
	if( !this._elPane && !inCallback ){
		setTimeout( GIPROTOTYPE.bind(this, function(){this._parseEnvironment(1)}), 4000);
		return;
	}
	
	// Stake a claim
	this._elPaneContent = this._contactsDoc.createElement("DIV");
		this._elPaneContent.className = "gtd-contactpane";
	this._elPane.appendChild( this._elPaneContent);
	this.activePane(false);
	
	// Add observers
	this._eventObservers.observe( this._elManagerTabs, "mousedown", this._clickTabs, true );
	this._eventObservers.observe( this._elManagerList, "mouseup", this._clickList, false );
	this._eventObservers.observe( this._elPaneContent, "click", this._clickPane, true);
	
	

}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI parseEnvironemtn\n" + e.toString());
}	
};

ContactsUI.prototype._clickTabs = function(event){
	// Clicked the tabs box; confirm it was an actual tab clicked
	// If so, wipe out the current names list and clear the elPane
try{	
	var el = GIPROTOTYPE.element(event);
	if( this._gtdinboxPage.gmailDOM.test("contact-tab", el) ){
		this._selected.length = 0;
		this._elPaneContent.innerHTML = "";
		this.activePane(false);
	}else{
		this.refreshPane();
		this.activePane(true);
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI clickTabs\n" + e.toString());
}

};

ContactsUI.prototype.activePane = function(v){
	if( typeof v=="undefined" ) return !(this._elPaneContent.style.display=="none");
	this._elPaneContent.style.display = v? "":"none";
	if( !v ){
		this.destroyFilterPopup();
	}
};

ContactsUI.prototype._clickList = function(event){
	// Clear selected and rebuild, storing names and emails

try{	
	
	setTimeout(GIPROTOTYPE.bind(this, this._clickListParseCurrent), 50);	
	
	
	// Better to monitor node changes to list, and refresh based on #selected items?
	
}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI clickList\n" + e.toString());
}
};
ContactsUI.prototype._clickListParseCurrent = function(){
	// Extract all selected items
try{
	this._selected.length = 0;
	var els = this._gtdinboxPage.gmailDOM.elements("contacts-list", null, this._contactsDoc, this._elContactsBody);
	for( var i = 0; i < els.snapshotLength; i++ ){
		if( els.snapshotItem(i).checked ){
			var li = this._gtdinboxPage.gmailDOM.parseElement("contacts-list-item", els.snapshotItem(i));
			this._selected.push(li);
		}
	}
	if( this._selected.length > 0 ){
		this.refreshPane();
		this.activePane(true);
	}else{
		this.activePane(false);
	}
	
}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI _clickListParseCurrent\n" + e.toString());
}
};

ContactsUI.prototype.refreshPane = function(){
	// Refresh Tasks, Projects, Contexts, References, Files & Search for currently selected users

	this.destroyFilterPopup();
	this._elPaneContent.innerHTML = "";
	
	var elTitle = this._doc.createElement("DIV");
		elTitle.innerHTML = this._gtdinboxPage.stringBundle.getString("Contacts.PaneTitle");
		elTitle.className = "title";
	this._elPaneContent.appendChild( elTitle );
	
	var settings = this._gtdinboxPage.settings;
	
	// Create a contacts list for the stored procedures
	var names = [];
	var contacts = [];
	for( var i = 0; i < this._selected.length; i++ ){
		names.push( this._selected[i][0] );
		contacts.push( this._selected[i][1] );
	}
 	
 	this._parentSearch = GIPROTOTYPE.restrictSearchToUser(names, true) + " ";
 	
	// Create structure:
	this._elPaneLabels = this._doc.createElement("DIV");
		this._elPaneLabels.className = "labels-container";
	this._elPaneContent.appendChild( this._elPaneLabels );
	
	// Load the labels:
	for( t in settings.labels.types ){
		var elLabels = this._labels.getLabelsEl(t);
		
		// Create header title
		var title = t;
		try{
			title = this._gtdinboxPage.stringBundle.getString("Contacts.Types." + t);
		}catch(e){}
		
		if( t!="Statuses" && t!="Old" && t!="Misc" ){ // Filter list for approved items
			// Retrieve a list of 'approved' labels
			var labelsHash = this._gtdinboxPage.sp.getRankedLabelsByContact(settings.labels.types[t].prefix, contacts, true);
			this._filterLabels(labelsHash, elLabels, t);
		}
		
		// Create the show hider
		if( elLabels.childNodes[1].childNodes.length>0 ){	// elLabels = <div class=title>Old</div><div class='labels'>LABELSHERE</div>
			var els = elLabels.getElementsByTagName("*");
			for( var i = els.length - 1; i>=0; i-- ){
				if( els[i].className=="title" ) els[i].innerHTML = title;
				if( els[i].getAttribute("gtdLabelName") ){
					els[i].setAttribute("gtdSearch", this._parentSearch + GIPROTOTYPE.searchableLabel(els[i].getAttribute("gtdLabelName"))); 
					this._appendCommands(els[i], false, true);
				}
			}
			
			var showHider = new Showhider(this._gtdinboxPage, "contacts-gtd-" + t, {doc:this._doc, type:"attach", el:elLabels, titleClass:"title", show:false});
			this._showHiders.push( showHider );
			this._elPaneLabels.appendChild( showHider.el );
		}		
	}
	
	// Associated Contacts
	var rankedContacts = this._gtdinboxPage.sp.getRankedContactsByContact(contacts);
	var elContacts = this._doc.createElement("DIV");
		elContacts.className = "labels";
	for( var i = 0; i < rankedContacts.length; i++ ){
		var elContact = this._doc.createElement("DIV");
			elContact.setAttribute("gtdSearch", this._parentSearch + GIPROTOTYPE.restrictSearchToUser(rankedContacts[i], true));
			elContact.innerHTML = rankedContacts[i];
			elContact.className = "label";
			elContact.setAttribute("email", rankedContacts[i]);
			elContact.setAttribute("gtdName", rankedContacts[i]);
			elContact.setAttribute("gtdType", "Contact");
		elContacts.appendChild( elContact );
		this._appendCommands(elContact, false, true);
	}
	var showHider = new Showhider(this._gtdinboxPage, "contacts-gtd-contact", {doc:this._doc, type:'create', elParent:this._elPaneLabels, 'title':this._gtdinboxPage.stringBundle.getString("Contacts.Types.Contacts"), elContent:elContacts});
		showHider.el.className = "labels-group";
		showHider.elTitle.title = this._gtdinboxPage.stringBundle.getString("Contacts.Types.Contacts.tooltip");
	this._showHiders.push( showHider );
	
	
	// Misc Actions
	var elMisc = this._doc.createElement("DIV");
		elMisc.className = "misc-actions";
	this._elPaneContent.appendChild( elMisc );
	
	// Associated Files
	var elFiles = this._doc.createElement("DIV");
		elFiles.className = "files";
		elFiles.innerHTML = this._gtdinboxPage.stringBundle.getString("Contacts.AssociatedFiles")
		elFiles.setAttribute("gtdSearch", this._parentSearch + "has:attachment");
	this._appendCommands(elFiles, false, false);
	elMisc.appendChild( elFiles );
	
	// Search
	var elSearch = this._doc.createElement("DIV");
		elSearch.className = "search";
	var elSearchInput = this._doc.createElement("INPUT");
		elSearchInput.setAttribute("type", "text");
	elSearch.appendChild( elSearchInput );
	var elSearchCmd = this._doc.createElement("BUTTON");
		elSearchCmd.innerHTML = this._gtdinboxPage.stringBundle.getString("Contacts.SearchButton");	
	elSearch.appendChild( elSearchCmd );
	elMisc.appendChild( elSearch );

	var elClear = this._doc.createElement("DIV");
		elClear.style.clear = "both";
	this._elPaneContent.appendChild( elClear );

};

ContactsUI.prototype._filterLabels = function(labelsHash, elLabels, type){
	// Filter the labels to only include those in labelsHash
	// If newTitle provided, overwrite the original title
	
	var elAll = elLabels.cloneNode(true);
	
	var els = elLabels.getElementsByTagName("*");
	var elLabelsInner = null;
	var removed = false;
	for( var i = els.length - 1; i>=0; i-- ){
		if( els[i].className=="labels" ) elLabelsInner = els[i];
		if( els[i].hasAttribute("gtdLabelSourceName") && !labelsHash[els[i].getAttribute("gtdLabelSourceName")] ){
			els[i].parentNode.removeChild(els[i]);
			removed = true;
		}
	}
	
	if( removed ){	// Add 'All items'
		var showHider = new Showhider(this._gtdinboxPage, "contacts-gtd-all-" + type, {doc:this._doc, type:"attach", el:elAll, titleClass:"title", show:false});
		showHider.setTitle( this._gtdinboxPage.stringBundle.getString("Contacts.LabelsAll") );
		this._showHiders.push( showHider );
		elLabelsInner.appendChild( showHider.el );	 
	}
	
};

ContactsUI.prototype._appendCommands = function(elLink, cannotPopout, canExpand){	// TODO this also appears in Dashboard, tidy up?
	var fAttrib = function(el){
			el.setAttribute("gtdSearch", elLink.getAttribute("gtdSearch"));
			el.setAttribute("gtdName", elLink.getAttribute("gtdName"));
			el.setAttribute("gtdLabelName", elLink.getAttribute("gtdLabelName"));
			el.setAttribute("gtdType", elLink.getAttribute("gtdType"));
			el.setAttribute("email", elLink.getAttribute("email"));
		};
		
	// Compartmentalise the old link inner html
	var elContent = this._doc.createElement("DIV");
		elContent.className = "body";
		elContent.innerHTML = elLink.innerHTML;
		fAttrib(elContent);
	elLink.innerHTML = "";
	elLink.appendChild( elContent );
	
	var elCmds = this._doc.createElement("DIV");
		elCmds.className = "commands";
	elLink.appendChild( elCmds );
		
	if( !cannotPopout ){
		var elPopout = this._doc.createElement("IMG");
			elPopout.className = "async-popuper";
			elPopout.src = "chrome://gtdinbox/skin/popout.png";
			elPopout.title = this._gtdinboxPage.stringBundle.getString("FilterPopup.tooltip.Open");	
			fAttrib(elPopout);
		elCmds.appendChild( elPopout );
	}
		
	if( elLink.getAttribute("gtdName") && canExpand ){
		var elExpander = this._doc.createElement("IMG");
			elExpander.className = "expander";
			elExpander.src = "chrome://gtdinbox/content/filter-extend.png";
			elExpander.title = this._gtdinboxPage.stringBundle.getString("FilterPopup.tooltip.Drill");	
		elCmds.appendChild( elExpander );
		fAttrib(elExpander);
	}
	
	var elClear = this._doc.createElement("DIV");
	elClear.style.clear = "both";
	elLink.appendChild( elClear );
};


ContactsUI.prototype._clickPane = function(event){
try{
	if( event.button!=0 ) return;
	
	var el = GIPROTOTYPE.element(event);
	
	if( el.nodeName=="BUTTON" ){	// search
		el = el.parentNode.getElementsByTagName("INPUT")[0];
		this._gtdinboxPage.search( this._parentSearch + " " + el.value );
		GIPROTOTYPE.stop(event);
	}else if( el.nodeName=="IMG" && el.className=="expander" ){
		this._clickExtend(el);
		GIPROTOTYPE.stop(event);
	}else{
		var searchStr = el.getAttribute("gtdSearch");
		if( searchStr ){
			GIPROTOTYPE.stop(event);
			this._gtdinboxPage.search(searchStr);
		}
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("Contacts _clickPane\n" + e.toString());
}
};

ContactsUI.prototype._clickExtend = function(el){	// TODO this also appears in Dashboard, tidy up?
	// Use the line-item to generate new popup
try{
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
		this._filterChild = null;
		//if( this._filterChildEl==el ) return;
	}
	
	var type = el.getAttribute("gtdType");
	var name = (type=="Contact")? [el.getAttribute("gtdName"),el.getAttribute("gtdName")] : el.getAttribute("gtdLabelName");
	var parentSearch = el.getAttribute("gtdSearch");
	this._filterChild = new FilterPopupUI( this._gtdinboxPage, name, type, el, [], [], parentSearch );
	this._filterChild.popup(el,{location:'right'});
	this._filterChildEl = el;
}catch(e){
	if( GTDDEBUGMODE ) alert("ContactsUI clickExtend\n" + e.toString());
}
};


ContactsUI.prototype.destroyFilterPopup = function(){
	if( this._filterChild ){	// turn off
		this._filterChild.destroy();
	}
};
ContactsUI.prototype.destroy = function(){
	this.destroyFilterPopup();
	for( var i = 0; i < this._showHiders.length; i++ ){
		this._showHiders[i].destroy();
	}

	this._eventObservers.destroy();
};